var express = require('express');
var router = express.Router();
var jwt = require("jsonwebtoken");
const secret = "goyangforum";  //秘钥
const { mysqlCreate } = require('./utils');
var mysql = require('mysql');

//连接数据库
let conn = mysqlCreate();

router.get('/', (req, res) => {
  conn = mysql.createConnection(conn.config); 
  // console.log(req.headers.authorization)
  //定义token验证中间件函数（应用于除登录外的每个请求）
  if (req.headers.authorization) {
    //获取客户端发送来的token
    const token = req.headers.authorization;
    jwt.verify(token, secret, (err, decoded)=>{
      if(err){
        console.log(err)
        res.json({code: -1})
      }else{
        let sql = `SELECT * FROM user where name = ${decoded.user}`; //创建数据库查询的语法
        conn.connect();
        conn.query(sql, function (err, result){
          if(err){
            console.log('[SELECT ERROR] - ',err.message);
            res.json({ code: -1 })
          }else{
            if(result.length == 0){
              res.json({code: -1, message:"用户不存在"})
            }else if(result[0].name !== decoded.user){
              res.json({code: -1, message:"用户信息不正确"})
            }else{
              res.json({code: 10000, message:"验证成功", content: result})
            }
          }
        });
        conn.end();
      }
    })
  }else{
    res.json({ code: -2, message: "没有正确的头信息"})
  }
})

//获取所有文章
// router.get('/', (req, res) => {
//   console.log(req.params)
//   conn = mysql.createConnection(conn.config); 
//   var sql = 'SELECT * FROM article where type';
//   conn.connect();
//   conn.query(sql, function (err, result) {
//     if(err){
//       console.log('[SELECT ERROR] - ',err.message);
//       res.json({ code: -1})
//     }else{
//       res.json({ code: 10000, message: "OK", data: result})
//       console.log(req.params + "=====")
//     } 
//   });
//   conn.end();
// })

module.exports = router;
